<script lang="ts" setup>
import { tagListColor } from '@/constant/tag'
import { getDictDataListAPI } from '@/views/admin/system/dict/utils/api'
import type { SysDictionaryDataType } from '@/views/admin/system/dict/utils/model'

type Props = {
  dictType: string
  type?: 'select' | 'radio' | 'checkbox' | 'tag'
  label?: string
  placeholder?: string
  name?: string
}

const inputValue = defineModel()
const dataList = ref<SysDictionaryDataType[]>([])
const { dictType, type } = withDefaults(defineProps<Props>(), {
  dictType: '',
  type: 'select',
  label: '',
  placeholder: '',
  name: ''
})

function getDictData() {
  getDictDataListAPI(dictType).then((res) => {
    dataList.value = res.data
    dataList.value = dataList.value.filter((item) => item.status == 1)
    if (inputValue.value == undefined) {
      dataList.value.forEach((item) => {
        if (item.dictDefault == 1) {
          if (type == 'checkbox') {
            inputValue.value = [...item.dictValue]
          } else {
            inputValue.value = item.dictValue
          }
        }
      })
    } else {
      if (type == 'checkbox') {
        inputValue.value = [...inputValue.value].map((item) => item + '')
      } else {
        inputValue.value = inputValue.value + ''
      }
    }
  })
}

watch(
  inputValue,
  () => {
    if (typeof inputValue.value == 'undefined') return
    if (typeof inputValue.value == 'string') return
    if (type == 'checkbox') {
      inputValue.value = [...inputValue.value].map((item) => item + '')
    } else {
      inputValue.value = inputValue.value + ''
    }
  },
  { deep: true }
)

onMounted(() => {
  if (dictType !== '') {
    getDictData()
  }
})
</script>

<template>
  <a-form-item v-if="type != 'tag'" :label="label as any" :name="name">
    <a-select v-if="type == 'select'" v-model:value="inputValue" :placeholder="placeholder">
      <a-select-option v-for="item in dataList" :key="item.id" :value="item.dictValue">
        {{ item.dictName }}
      </a-select-option>
    </a-select>
    <a-radio-group v-if="type == 'radio'" v-model:value="inputValue as any">
      <a-radio v-for="item in dataList" :key="item.id" :value="item.dictValue">
        {{ item.dictName }}
      </a-radio>
    </a-radio-group>
    <a-checkbox-group
      v-if="type == 'checkbox'"
      v-model:value="inputValue as any"
      :placeholder="placeholder"
    >
      <a-checkbox v-for="item in dataList" :key="item.id" :value="item.dictValue">
        {{ item.dictName }}
      </a-checkbox>
    </a-checkbox-group>
  </a-form-item>
  <div v-else>
    <span v-for="item in dataList" :key="item.id">
      {{ item }}
      <a-tag v-if="item.dictValue == inputValue" :color="tagListColor[item.dictValue]">
        {{ item.dictName }}
      </a-tag>
    </span>
  </div>
</template>

<style scoped></style>
